from django import forms
from django.core import validators
from django.contrib.auth.models import User

class RegistrationForm(forms.Manipulator):
   def __init__(self):
      self.fields = (
		forms.TextField(field_name='username', length=30, maxlength=30,
			is_required=True, validator_list=[validators.isAlphaNumeric, self.isValidUsername]),
      forms.TextField(field_name = 'firstname', length = 50, maxlength = 50, is_required = True),
      forms.TextField(field_name = 'lastname', length = 50, maxlength = 50, is_required = True),
			forms.EmailField(field_name='email', length=30, maxlength=30, is_required=True),
			forms.PasswordField(field_name='password_once', length=30, maxlength=30, is_required=True),
			forms.PasswordField(field_name='password_twice', length=30, maxlength=30, is_required=True, 
			validator_list=[validator.AlwaysMatchesOtherField('password1', 'Passwords must match')]),
            )
    def isValidUsername(self, field_data, all_data):
	    try:
		   User.objects.get(username=field_data)
        except User.DoesNotExist:
           return
        raise validators.ValidationError('The username %s is already taken' % field_data)
		def save(self, data):
			u = User.objects.create_user(data['username'],
					                         data['email'],
																	 data['password_once'])
			u.is_active = True
			u.save()
			return u
